using System.Collections;
using System;
using System.Collections.Generic;
using UnityEngine;

namespace Framework.Base{

    // 池对象接口
    public interface IPoolObj{

        // 从回收池取出
        void OnFetch();

        // 加入回收池
        void OnRecycle();

        
    }

    // 对象池
    public class Pool: Framework.Base.BaseObject{
        
        private Queue<IPoolObj> m_poolObjQueue = new Queue<IPoolObj>();
        
        protected int mPoolObjCnt = 0;

        protected Type mCreateType;

        public Pool(Type objType){
            this.mCreateType = objType;
        }

        public IPoolObj Create(){
            IPoolObj obj;
            if(this.mPoolObjCnt > 0){
                obj  = this.m_poolObjQueue.Dequeue();
            }
            else{
                obj = (IPoolObj)System.Activator.CreateInstance(this.mCreateType);
            }
            obj.OnFetch();
            return obj;
        }

        public void Recycle(IPoolObj pooObj){
            pooObj.OnRecycle();
            this.m_poolObjQueue.Enqueue(pooObj);
        } 

    }

    

    public class PoolMgr:BaseObject{

        private static readonly Dictionary<System.Type, Pool> m_poolDict = new Dictionary<Type, Pool>();

        public static T Create<T>(){
            Pool poolObj;
            Type type = typeof(T);
            if(!m_poolDict.TryGetValue(type, out poolObj)){
                poolObj = new Pool(type);
                m_poolDict[type] = poolObj;
            }
            return (T) poolObj.Create();
        }

        public static void Recycle(IPoolObj poolObj){
            Type type = poolObj.GetType();
            Pool pool;
            if(m_poolDict.TryGetValue(type, out pool)){
                pool.Recycle(poolObj);
            }
        }

    }


}